package com.mes.controller.manu;


import com.mes.entity.User;
import com.mes.service.manu.ManNeedleCartService;
import com.yy.base.common.action.BaseCtrl;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import com.yy.base.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * 人工针车
 */
@Controller
@RequestMapping("manNeedleCart")
public class ManNeedleCartController extends BaseCtrl {

    @Autowired
    private ManNeedleCartService manNeedleCartService;

    /**
     * 获取部位列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="getPositionList", method= RequestMethod.POST)
    public Message getPositionList(HttpServletRequest request) {
        Message msg = new Message();
        String orderNo = request.getParameter("orderNo");

        //判断工单是否存在
        Map<String,Object> orderMap = manNeedleCartService.emesoJobOrder(orderNo);
        if (null == orderMap || orderMap.isEmpty()) {
            msg.setErrorMessage("工单不存在！");
            return msg;
        }

        //找到上一道工序（判断人工针车是否需要验证上一道工序必须完工）
        String nextRouteNos = manNeedleCartService.getPreRouteNo(orderNo);

        //校验上一环节是否已完工
        if (StringUtil.isNotEmpty(nextRouteNos)) {
            String result = manNeedleCartService.preRouteFinished(nextRouteNos, orderNo);
            if (StringUtil.isNotEmpty(result)) {
                msg.setErrorMessage("上一道工序【" + result + "】尚未完工！");
                return msg;
            }
        }

        //查询需要人工针车环节的部位列表
        List<Map<String,Object>> list = manNeedleCartService.getPositionList(orderNo);
        msg.setData("positionList", list);

        //查询工艺文件
        // Map<String,Object> fileMap = manNeedleCartService.getWworkroutePath(orderNo);
        // msg.setData("documentUrl", fileMap.get("workroute"));

        return msg;
    }

    /**
     * 部位完工
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="addPositionFinished", method= RequestMethod.POST)
    public Message addPositionFinished(HttpServletRequest request) {
        String emesoJobOrderId = request.getParameter("orderId");
        String emesPbomItemId = request.getParameter("PBOM_ID");
        String status = request.getParameter("status");

        Message msg = new Message();

        try {
            User user = UserUtil.getLoginUser(request);
            Integer result = manNeedleCartService.addPositionFinished(emesoJobOrderId, emesPbomItemId, status, user);
            if (result > 0) {
                msg.setOkMessage("修改部位报工状态成功！");
            } else {
                msg.setErrorMessage("修改部位报工状态失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setErrorMessage("修改部位报工状态失败！");
        }

        return msg;
    }


    /**
     * 人工针车完工
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="processFinished", method= RequestMethod.POST)
    public Message processFinished(HttpServletRequest request) {
        Message msg = new Message();
        String orderNo = request.getParameter("orderNo");

        try {
            User user = UserUtil.getLoginUser(request);
            Integer result = manNeedleCartService.addProcessFinished(orderNo, user);
            if (result > 0) {
                msg.setOkMessage("人工针车报工成功！");
            } else {
                msg.setErrorMessage("人工针车报工失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setErrorMessage("人工针车报工失败！");
        }

        return msg;
    }

    /**
     * 预览文件
     * @param request
     * @param response
     */
    @RequestMapping(value="downFile/{orderNo}", method= RequestMethod.GET)
    public void downFile(@PathVariable(value = "orderNo") String orderNo, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        //查询工艺文件
        Map<String,Object> fileMap = null;
        String filePath = "";
        try {
            fileMap = manNeedleCartService.getWworkroutePath(orderNo);
            filePath = fileMap.get("workroute").toString();
            // 下载本地文件
            String fileName = filePath.substring(filePath.lastIndexOf("\\")+1).toString(); // 文件的默认保存名

            // 读到流中
            InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预览图片
     * @param request
     * @param response
     * @throws FileNotFoundException
     */
    @RequestMapping(value="downFileImage", method= RequestMethod.GET)
    public void downFileImage( HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        String filePath = URLDecoder.decode(request.getParameter("filePath"));

        // 下载本地文件
        String fileName = filePath.substring(filePath.lastIndexOf("\\")+1).toString(); // 文件的默认保存名

        // 读到流中
        InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 人工针车报工
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="jobBook", method= RequestMethod.POST)
    public Message jobBook(HttpServletRequest request) {
        Message msg = new Message();
        String orderNo = request.getParameter("orderNo");

        //判断工单是否存在
        Map<String,Object> orderMap = manNeedleCartService.emesoJobOrder(orderNo);
        if (null == orderMap || orderMap.isEmpty()) {
            msg.setErrorMessage("工单不存在！");
            return msg;
        }

        User user = UserUtil.getLoginUser(request);
        try {
            Integer result = manNeedleCartService.executeRgzcProcess(orderNo, user);
            if (null != result && result > 0) {
                msg.setOkMessage("人工针车报工成功！");
                if (result == 100) {
                    msg.setData("isShowPdf", 0);
                } else {
                    msg.setData("isShowPdf", 1);
                }
            } else {
                msg.setOkMessage("人工针车报工失败！");
            }
        } catch (Exception e) {
            msg.setErrorMessage(e.getMessage());
            e.printStackTrace();
        }

        return msg;
    }

}
